<template>

    <div class="bg-container">

        <Toolbar :items="['新增', '删除', '导出', '导入']" @add="addHandler" @del="deleteHandler"></Toolbar>
    </div>

    <div class="gang"></div>

    <div style="padding:10px;box-sizing: border-box;">
        <a-tabs   :lazy-load="true">
            <a-tab-pane title="用户列表">

                <a-table stripe :bordered="true" :columns="tableColumns"
                    :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="selectedRowKeys"
                    :loading="table.tableLoading" :data="table.dataList" :pagination="pagination" :rowKey="rowKey">
                    <template #action="{ record }">
                        <a-space>
                            <a-button type="primary" size="small" status="warning" @click="editHandler(record)">
                                <template #icon>
                                    <icon-edit />
                                </template>
                                修 改
                            </a-button>
                            <a-button type="primary" size="small" @click="changePwd(record)">
                                <template #icon>
                                    <icon-edit />
                                </template>
                                更换密码
                            </a-button>
                        </a-space>
                    </template>
                </a-table>


            </a-tab-pane>
        </a-tabs>
    </div>
    <a-drawer ok-text='保存' cancel-text='关闭'  :drawer-style="{'zIndex':9999}" :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="cancel">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="vertical" :model="dataForm">
                <a-form-item label="用户名" field="username" :rules="{ required: true, message: '请输入用户名' }">
                    <a-input placeholder="" v-model="dataForm.username" />
                </a-form-item>
                <a-form-item label="昵称" field="nickName" :rules="{ required: true, message: '请输入昵称' }">
                    <a-input placeholder="" v-model="dataForm.nickName" />
                </a-form-item>

            </a-form>
        </div>
    </a-drawer>
    <a-modal :visible="pageData.changePwd" title="修改密码" @ok="changePasswordHandler"
        @cancel="pageData.changePwd = false">
        <a-form :model="pwdData">
            <a-form-item label="密码">
                <a-input type="password" v-model="pwdData.pwd" placeholder=""></a-input>
            </a-form-item>
            <a-form-item label="确认密码">
                <a-input type="password" v-model="pwdData.confirmPwd" placeholder=""></a-input>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import md5 from 'js-md5'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';


interface Firm {
    name: string,
    id: number
}

interface Role {
    "id": number | string,
    "username": string,
    "nickName": string,
    "deleteState": number | string,
    "gmtCreate": string,
    "gmtModified": string
}
export default {
    name: "RoleList",
    setup() {
        function doRefresh() {
            get({
                url: "/admin/acl/user/index",
                data: {
                    page: pagination.page,
                    limit: pagination.pageSize,
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.items);
                        pagination.setTotalSize(data.total);
                    }
                })
                .catch(console.log);
        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");

        const tableColumns = useTableColumn([
            {
                title: "用户名",
                key: "username",
                dataIndex: "username",
                width: 150,
            },
            {
                title: "昵称",
                key: "nickName",
                dataIndex: "nickName",
                width: 150,
            },
            {
                title: '操作',
                key: "id",
                slotName: 'action',
                width: 150, fixed: 'right'
            }
        ]);
        const pageData = reactive<{
            gcList: Firm[];

            showAdd: boolean,
            sideTitle: string,
            changePwd: boolean
        }>({
            gcList: [],
            changePwd: false,
            showAdd: false,
            sideTitle: '新增登录账号'
        });

        onMounted(() => {
            doRefresh();
        });
        const queryData = reactive({
            firm: "",
            clothType: ""
        });
        const addHandler = () => {

            pageData.showAdd = true

            pageData.sideTitle = '新增登录账号'

        }
        const dataForm = reactive<Role>({
            "id": "",
            "nickName": '',
            "username": "",
            "deleteState": 0,
            "gmtCreate": "",
            "gmtModified": ""
        })
        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    formRef.value?.validate().then((err) => {
                        if (!err) {
                            if (pageData.sideTitle === "新增登录账号") {
                                dataForm.deleteState = "false"
                                dataForm['password'] = 'e10adc3949ba59abbe56e057f20f883e'
                                post({
                                    url: "admin/acl/user/save",

                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "新增成功",
                                            duration: 5000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        });
                                    }
                                    doRefresh();
                                });
                            } else {
                                dataForm['password'] = ''
                                post({
                                    url: "admin/acl/user/update",
                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "修改成功",
                                            duration: 5000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        });
                                    }
                                    doRefresh();
                                });
                            }
                        }
                    });
                }

            })
        }
        const deleteHandler = () => {
            if (selectedRowKeys.value.length === 0) {
                return
            }

            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    post({
                        url: 'admin/acl/user/batchRemove?idList=' + selectedRowKeys.value.join(','),
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                        } else {
                            Message.success({
                                content: '修改失败',
                                duration: 5000
                            })
                        }
                        doRefresh()
                    })
                }
            })
        }
        const cancel = () => {
            formRef.value?.resetFields()

            dataForm.nickName = ''
            dataForm.username = ''

            pageData.showAdd = false
        }
        const editHandler = (record: Role) => {
            dataForm.id = record.id
            dataForm.nickName = record.nickName
            dataForm.username = record.username
            pageData.sideTitle = '修改用户资料'
            pageData.showAdd = true
        }
        const pwdData = reactive({
            curId: '',
            pwd: '',
            confirmPwd: ''
        })
        const changePwd = (record: any) => {
            pwdData.curId = record.id
            pwdData.confirmPwd = ''
            pwdData.pwd = ''
            pageData.changePwd = true
        }
        const changePasswordHandler = async () => {
            if (pwdData.pwd !== pwdData.confirmPwd) {
                Message.error({
                    content: '两次输入密码不一样！',
                    duration: 5000
                })
                return
            }
            let result = await post({
                url: "admin/acl/user/update",
                data: {
                    password: md5(pwdData.pwd)
                }
            })

            console.log(result)
            if (result.code === 200) {

                return true
            } else {
                Message.error({
                    content: '修改失败',
                    duration: 5000
                })
                return false
            }

        }
        return {
            changePasswordHandler,
            changePwd,
            pwdData,
            cancel,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData
        };
    },
    components: { Toolbar }
}
</script>
<style scoped lang="less">



</style>